//
//  NSDate+Exension.swift
//  WeiBo
//
//  Created by 李立达 on 15/12/13.
//  Copyright © 2015年 heima11. All rights reserved.
//

import UIKit


extension NSDate{

    
    class func sinaNSdate(creatStr: String) -> NSDate?{
    
    
        let dt = NSDateFormatter()
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dt.locale = NSLocale(localeIdentifier: "en_US")
        
        let creatDate = dt.dateFromString(creatStr)
        
        return creatDate
    }
    
    
    var sinaDateString : String {
    
        let dt = NSDateFormatter()
    
        dt.locale = NSLocale(localeIdentifier: "en_US")
        
        let calendar = NSCalendar.currentCalendar()
        
        if isThisYear(self)
        {
            dt.dateFormat = "是今年"
            if calendar.isDateInToday(self)
            {
                
                let result = -self.timeIntervalSinceNow
                
                if result < 60
                {
                    dt.dateFormat = "刚刚"
                }
                else if result < (60*60)
                {
                    dt.dateFormat = "\(Int(result/60))分钟前"
                }
                else
                {
                    dt.dateFormat = "\(Int(result/(60*60)))小时前"
                }
            }
            else if calendar.isDateInYesterday(self)
            {
                dt.dateFormat = "昨天 HH:mm"
            }
            else
            {
            
                dt.dateFormat = "yyyy-MM-dd HH:mm"
            }
        }
        else
        {
        
            
        }
        
        return dt.stringFromDate(self)
    }
    
    
    
    private func isThisYear(date:NSDate)->Bool{
        
        
        let currentDate = NSDate()
        
        let dt = NSDateFormatter()
        
        dt.dateFormat = "yyyy"
        
        dt.locale = NSLocale(localeIdentifier: "en_US")
        
        let dateStr = dt.stringFromDate(date)
        let currentDatestr = dt.stringFromDate(currentDate)
        
        return (dateStr as NSString).isEqualToString(currentDatestr)
    }
}
